// pages/user/orderDetails/orderDetails.js
import orderIndex from '../../../api/order';
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX: app.globalData.isIphoneX,
    orderNo: '',
    orderInfo: null,

    servicetimeInterval: '',
    systimestamp: '',
    isBtn:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      orderNo: options.orderNo
    })
    this.getOrderInfo()
  },
  getOrderInfo() {
    orderIndex.apiOrderInfo({ orderNo: this.data.orderNo }).then(res => {
      var orderInfo = res.data
      orderInfo.endTime = ''
      if (res.data.status == 0) {
        var serverLocalDate = new Date().getTime();
        //调用函数开始计时
        this.serverLocalDate(serverLocalDate);
        orderInfo.endTime = this.getendTime(orderInfo.createTime)
      }
      this.setData({
        orderInfo: orderInfo
      })
    })
  },
  getendTime(time) {
    let now = new Date(time); // 获取当前时间
    // 将当前时间加上24小时
    let futureTime = new Date(now.getTime() + 24 * 60 * 60 * 1000); // 24小时的毫秒数 
    // 格式化时间为年-月-日 时:分:秒
    let year = futureTime.getFullYear();
    let month = String(futureTime.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以需要+1，并使用padStart确保是两位数
    let day = String(futureTime.getDate()).padStart(2, '0');
    let hours = String(futureTime.getHours()).padStart(2, '0');
    let minutes = String(futureTime.getMinutes()).padStart(2, '0');
    let seconds = String(futureTime.getSeconds()).padStart(2, '0');
    let formattedDate = `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
    return formattedDate
  },
  afterSalesOrderservice(e) {
    var item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/pages/user/afterSalesOrderservice/afterSalesOrderservice?item=${JSON.stringify(item)}`,
    })

  },
  lookafterSalesOrderservice(e){
    wx.navigateTo({
      url: `/pages/user/afterSalesOrder/afterSalesOrder`,
    })
  },
  goShopDetails(e) {
    var row = e.currentTarget.dataset.row
    wx.navigateTo({
      url: `/pages/home/productDetails/productDetails?id=${row.productId}`,
    })
  },
  //查看物流
  getlogistics() {
    wx.navigateTo({
      url: `/pages/user/logistics/logistics?orderNo=${this.data.orderInfo.orderNo}&&type=1`,
    })
  },
  behalfPay() {
    wx.navigateTo({
      url: `/pages/home/behalfPayment/behalfPayment?amount=${this.data.orderInfo.amount}&orderNo=${this.data.orderInfo.orderNo}&type=share`,
    })
  },
  //申请发票
  getInvoice() {
    var orderNo = this.data.orderInfo.orderNo
    wx.navigateTo({
      url: `/pages/user/invoice/invoice?orderNo=${orderNo}`,
    })
  },
  //取消订单
  cancellationOrder(e) {
    var that = this
    var opt = {
      orderNo: this.data.orderInfo.orderNo
    }
    if(this.data.isBtn){
      return false
    }
    this.setData({
      isBtn:true
    })
    setTimeout(()=>{
      that.setData({
        isBtn:false
      })
    },2000)
    
    
    if (this.data.orderInfo.status == 1) {
      wx.requestSubscribeMessage({
        tmplIds: ['SRsRyuTY8dIxP61UcjuhNlTThi9T-_8aaGzYNjutpHg'],
        complete(complete) {
          wx.showModal({
            title: '提示',
            content: '确认取消当前订单？',
            success(res) {
              if (res.confirm) {
                orderIndex.apiCancelOrder(opt).then(res => {
                  wx.showToast({
                    title: '订单取消成功',
                    icon: 'none',
                    duration:3000,
                  })
                  that.getOrderInfo()
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '确认取消当前订单？',
        success(res) {
          if (res.confirm) {
            orderIndex.apiCancelOrder(opt).then(res => {
              wx.showToast({
                title: '订单取消成功',
                icon: 'none',
                duration:3000,
              })
              that.getOrderInfo()
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }




  },
  confirmReceiptGoods() {
    var that=this
    if(this.data.isBtn){
      return false
    }
    this.setData({
      isBtn:true
    })
    setTimeout(()=>{
      that.setData({
        isBtn:false
      })
    },2000)
    var opt = {
      orderNo: this.data.orderInfo.orderNo
    }
    
    wx.showModal({
      title: '提示',
      content: '请先确认已经收到货',
      success(res) {
        if (res.confirm) {
          orderIndex.apiConfirmReceipt(opt).then(res => {
            wx.showToast({
              title: '确认收货成功',
              icon: 'none',
              duration:3000,
            })
            that.getOrderInfo()
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //再来一单
  buyAgain(e) {
    var that=this
    if(this.data.isBtn){
      return false
    }
    this.setData({
      isBtn:true
    })
    setTimeout(()=>{
      that.setData({
        isBtn:false
      })
    },2000)
    var opt = {
      orderNo: this.data.orderInfo.orderNo
    }
    wx.showModal({
      title: '提示',
      content: '确认再次购买当前产品？',
      success(res) {
        if (res.confirm) {
          orderIndex.apiOneMoreOrder(opt).then(res => {
            var row = res.data.details
            wx.setStorageSync('shopCartList', row)
            wx.navigateTo({
              url: '/pages/home/orderConfirm/orderConfirm',
            })
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //立即支付
  payNow(e) {
    var that=this
    if(this.data.isBtn){
      return false
    }
    this.setData({
      isBtn:true
    })
    setTimeout(()=>{
      that.setData({
        isBtn:false
      })
    },2000)

    this.payOrder(this.data.orderInfo.orderNo, this.data.orderInfo.relAmount)
  },
  payOrder(orderNo, amount) {
    var that = this
    wx.showLoading({
      title: '支付中'
    });
    orderIndex.apiSubmiPay({ orderNo: orderNo }).then(res => {
      wx.requestPayment({
        timeStamp: res.data.timeStamp,
        nonceStr: res.data.nonceStr,
        package: res.data.package,
        signType: res.data.signType,
        paySign: res.data.paySign,
        success: (res) => {
          setTimeout(function () {
            wx.hideLoading();
          }, 1500)
          if (res.resultCode == 6001) {
            wx.showToast({
              title: '取消支付',
              icon: 'none',
              duration:3000,
              success: function () {
                setTimeout(function () {
                  wx.hideLoading();
                }, 1500)
              }
            })
          } else if (res.resultCode == 6002) {
            wx.showToast({
              title: '网络连接出错,请检查网络连接后重试',
              icon: 'none',
              duration:3000,
              success: function () {
                setTimeout(function () {
                  wx.hideLoading();
                }, 1500)
              }
            })
          } else {
            wx.redirectTo({
              url: `/pages/home/payResult/payResult?amount=${amount}&&orderNo=${orderNo}`,
            })
          }
        },
        fail: (res) => {
          console.log(res)
          wx.showToast({
            title: "取消支付",
            icon: "none",
            duration:3000
          })

        }
      });
    })
    // wx.navigateTo({
    //   url: `/pages/home/choosePay/choosePay?amount=${amount}&&orderNo=${orderNo}`,
    // })
  },
  //服务器系统时间开始计时
  serverLocalDate: function (serverLocalDate) {
    var _this = this;
    let newDate = serverLocalDate;
    _this.setData({
      servicetimeInterval: setInterval(function () { // 循环执行  
        newDate = (newDate / 1000 + 1) * 1000;
        _this.setData({
          systimestamp: newDate
        })
      }, 1000)  // 每秒执行一次以达到更新时间的目的
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.orderNo) {
      this.getOrderInfo()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearInterval(this.data.servicetimeInterval)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.servicetimeInterval)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})